import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { intl } from '@/utils';
import { useModel } from 'umi';
import { CpasIcon, DevToolBar, DevGridSearchIpt } from '~/public/cpas-ui';
import { Item } from 'devextreme-react/toolbar';
import SelectBox from 'devextreme-react/select-box';
import TextBox from 'devextreme-react/text-box';
import TableComponents from './components/TableComponents';
import DropDownBoxList from './components/DropDownBoxList';
import ReportFinancialToResetMonth from './components/ReportFinancialToResetMonth';
import './index.less'

import { adjustingEntry, assistSDB, getAccountInfo, getDataSubjectSDB, getSubjectLevel, getSubjectList, getSubjectSDB, reCalReportItemsData, subjectSDB } from './service';
import { Button, CheckBox, LoadPanel } from 'devextreme-react';
import AccountTabs from './components/AccountTabs';
import notify from 'devextreme/ui/notify';
import { flattenTreeDataWithLeafCheck } from './util';
// import PubSub from 'pubsub-js';

const ReportFinancial = (props: any) => {
  // const { isShowGloablLoad }: any = useModel('useAdjustModel');
  const { initialState } = useModel('@@initialState');
  const { dbname, sjnd } = initialState?.curPart as API.CurPart;
  const { username } = initialState?.curUser as API.CurUser;
  // const { accountInfo, setAccountInfo } = useModel('useAdjustModel');
  const ToResetRef = useRef<any>();
  const DataTreeRef = useRef<any>();
  const AccountRef = useRef<any>();
  const accountYearRef = useRef<any>();

  // const [PaperData, setPaperData] = useState<{
  //   displayName?: string | undefined,
  //   byMonth?: any,
  //   data_ID?: any,
  //   data?: any[] | undefined,
  // }>({
  //   displayName: '',
  //   byMonth: '',
  //   data_ID: '',
  //   data: [],
  // })



  const [TextValue, setTextValue] = useState<any>('');

  const [accountYearData, setAccountYearData] = useState<any[]>([]);
  const [accountTreeList, setAccountTreeList] = useState<any[]>([]);
  const [subjectSDBData, setSubjectSDBData] = useState<any[]>([]);
  const [SubjectLevelData, setSubjectLevelData] = useState<any[]>([]);
  const [isShowGloablLoadInit, setIsShowGloablLoadInit] = useState<boolean>(false);

  const [dataRef, setDataRef] = useState({});

  const [subjectLevel, setSubjectLevel] = useState<string>('全部');
  const [accountYear, setAccountYear] = useState<string>('');
  const [timeData, setTimeData] = useState<string>('');
  const [selDefaultValue, setSelDefaultValue] = useState<any>('');

  const [CheckBoxVaue, setCheckBoxVaue] = useState<boolean>(false);
  // const [treeData, setTreeData] = useState<any>([]);
  // const [gridDataList, setGridDataList] = useState<any>([]);
  const treeData = useRef<any>([]);
  const gridDataList = useRef<any>([]);

  const Divstyle: React.CSSProperties = { display: 'flex', alignItems: "center", justifyContent: "center", };
  const Titlestyle: React.CSSProperties = { marginRight: "8px" }

  // 浏览器的高度 默认设置为0；
  const [resizeHeight, setResizeHeight] = useState<any>(0);
  const [resizeWidth, setResizeWidth] = useState<any>(0);

  const resizeUpdate = () => {
    // 通过事件对象获取浏览器窗口的高度
    // const h = e.target.innerHeight;
    // const w = e.target.innerWidth;
    // console.log(e, '@@@ e.target');
    const h = window.innerHeight;
    const w = window.innerWidth;
    console.log(w, h, '@@@ window.inner');
    setResizeHeight(h);
    setResizeWidth(w);
  };

  const changeTimes = () => {
    setTimeData(`${new Date().getTime()}`);
  }


  const getFetchData = async () => {
    const auditAdjustId: any = window.localStorage.getItem(`selectDefaultTool_${dbname}`);
    const tempYear = JSON.parse(auditAdjustId)?.tabledataId ?? sjnd;
    let findTemp = -2;
    const res: any = await getAccountInfo({ dbname });
    if (res.success) {
      findTemp = res.data.findIndex((item: any) => {
        return tempYear === item.Data_ID
      });
      const tempIndex = findTemp >= 0 ? findTemp : 0;
      const DataId = res.data[tempIndex]?.Data_ID;
      const displayNames = res.data[tempIndex]?.displayName;
      setSelDefaultValue(displayNames);
      res.data.forEach((item: any, index: any) => {
        item.index = index
        return item
      });
      setAccountYearData(res.data);
      const DataIdByMonth = res.data[findTemp]?.byMonth;
      setTextValue(`${DataIdByMonth}`);
      accountYearRef.current = DataId;
      setAccountYear(DataId);
    }
  }



  // setTimeout(() => {
  //   changeCurNode(flatData[0]);
  // }, 300);



  useEffect(() => {
    // 页面变化时获取浏览器窗口的大小 
    window.addEventListener('resize', resizeUpdate);
    resizeUpdate();
    getFetchData();
    return () => {
      // 组件销毁时移除监听事件
      window.removeEventListener('resize', resizeUpdate);
    }
  }, []);

  const getSubjectLevelData = async () => {
    const res = await getSubjectLevel({
      dbname,
      Data_ID: accountYear,
      isHasFZZ: CheckBoxVaue
    });
    if (res) {
      res.push({ JC: "末" })
      res.unshift({ JC: "全部" })
      const JCdata = res.map((item: any) => {
        if (item.JC !== '全部') {
          return item.JC + '级'
        } else {
          return item.JC
        }
      })
      setSubjectLevelData(JCdata);
    }
  };

  const changeCurNode = (nodeObj: any) => {
    DataTreeRef.current.ProjectTreeRef(nodeObj);
  };



  // 获取树数据
  const getSubjectListDatas = async () => {
    console.log(accountYear, 'AccountDataID-------');
    const res = await getSubjectList({
      dbname,
      Data_ID: accountYear,
      isHasFZZ: CheckBoxVaue,
    });
    if (res.success) {
      setAccountTreeList(res.data);

      const flatData = flattenTreeDataWithLeafCheck(res.data); // 转换为平铺结构并检查叶子节点
      console.log(`🚀--Nice ~ getSubjectListDatas ~ flatData:`, flatData)
      treeData.current = flatData;
      setAccountTreeList(flatData);
      setTimeout(() => {
        changeCurNode(flatData[0]);
      }, 300);

    }
  };
  // 获取表格数据
  const getSubjectSDBDatas = async () => {
    const res = await getSubjectSDB({
      dbname,
      Data_ID: accountYear,
      isHasFZZ: CheckBoxVaue,
    });
    if (res.success) {
      gridDataList.current = res.data;
      setSubjectSDBData(res.data);
    }
  };

  const reloadTreeAndTable = async () => {
    await getSubjectListDatas();
    await getSubjectSDBDatas();
  }

  const changeDataFun = useCallback((r: any) => {
    if (treeData.current?.length) {
      let tempTreeData = [];
      if (r === "全部") {
        tempTreeData = treeData.current;
      } else {
        tempTreeData = treeData.current.filter((item: any) => {
          return item.KMLX && item.KMLX.includes(r)
        })
      }
      setAccountTreeList(tempTreeData);
    }
    if (gridDataList.current.length) {
      let tempTableData = [];
      if (r === "全部") {
        tempTableData = gridDataList.current;
      } else {
        tempTableData = gridDataList.current.filter((item: any) => {
          return item.KMLX && item.KMLX.includes(r)
        })
      }
      setSubjectSDBData(tempTableData);
    }
    changeTimes();
  }, [setSubjectSDBData, setAccountTreeList]);

  // 获取列表的点击项 
  // 后期获取list的数据 获取到给tabs进行处理
  const onSelectionChangeds = (e: any) => {
    if (AccountRef.current) {
      const v: any = window.localStorage.getItem(`selectDefaultTool_${dbname}`);
      let selectDefaultIDs = JSON.parse(v);
      selectDefaultIDs = { ...selectDefaultIDs, tabledataId: e.selectedItem.Data_ID };
      // 本地存储 持久化数据
      window.localStorage.setItem(`selectDefaultTool_${dbname}`, JSON.stringify(selectDefaultIDs));
      AccountRef.current.show('0');
      setSubjectLevel("全部");
      getFetchData();
    }
  }



  useEffect(() => {
    if (accountYear) {
      setDataRef(DataTreeRef.current.DevGridRefStates());
      getSubjectLevelData();
      reloadTreeAndTable();
      changeTimes();
    }
  }, [accountYear, CheckBoxVaue]); //accountYear, CheckBoxVaue

  // 选中 类型 的每一个状态
  // const ListState = (v: any) => {
  //   switch (v.id) {
  //     case '0': {
  //       DataTreeRef.current.DataGridColumnStates(true);
  //       break;
  //     }
  //     case '1': {
  //       DataTreeRef.current.DataGridColumnEndStates(true);
  //       break;
  //     }
  //     case '2': {
  //       DataTreeRef.current.DataGridColumnReviewStates(true);
  //       break;
  //     }
  //   }
  // }

  function Content(r: string) {
    setTextValue(r);
  }






  const changeCategoryMenuOptions = {
    items: [
      {
        icon: 'iconfont icon-ellipsis',
        items: [
          {
            ID: "0",
            text: '初始化',
            items: [
              {
                ID: "2",
                text: '当前账套',
              },
              {
                ID: "3",
                text: '全部账套',
              },
            ]
          },
          {
            ID: "1",
            text: '重算调整数',
          },
        ],
      },
    ],
    onItemClick: async (e: any) => {
      switch (e.itemData.ID) {
        case '2': {
          console.log(accountYearRef.current, 'accountYearRef.currentDataIDRef.currentDataIDRef.current--------');

          const r = await subjectSDB({
            dbname,
            Data_ID: accountYearRef.current,
            byMonth: TextValue,
            isForceInit: true
          })
          const v = await assistSDB({
            dbname,
            Data_ID: accountYearRef.current,
            byMonth: TextValue,
            isForceInit: true
          })
          if (r || v) {
            notify('当前账套初始化成功', 'success', 2000)
            const rs = await reCalReportItemsData({
              dbname,
              Data_ID: accountYearRef.current,
              editUser: username,
              isRecalTZ: true
            })
            console.log(rs);
            if (rs) {
              reloadTreeAndTable();
              AccountRef.current.show('0');
            }
          } else {
            notify('初始化失败', 'error', 2000)
          }
        };
          break;
        case '3': {
          setIsShowGloablLoadInit(true);
          let successCount = 0;

          for (const item of accountYearData) {
            await new Promise((resolve) => setTimeout(resolve, 500));
            const [r, v] = await Promise.all([
              subjectSDB({
                dbname,
                Data_ID: item.Data_ID,
                byMonth: `${item.byMonth}`,
                isForceInit: true
              }),
              assistSDB({
                dbname,
                Data_ID: item.Data_ID,
                byMonth: `${item.byMonth}`,
                isForceInit: true
              })
            ]);

            if (r || v) {
              successCount++;
            }
          }

          if (successCount > 0) {
            for (const item of accountYearData) {
              await reCalReportItemsData({
                dbname,
                Data_ID: item.Data_ID,
                editUser: username,
                isRecalTZ: true
              });
            }
            setIsShowGloablLoadInit(false);
            notify('全部账套初始化成功', 'success', 2000);
            reloadTreeAndTable();
            AccountRef.current.show('0');
          } else {
            setIsShowGloablLoadInit(false);
            notify('初始化失败', 'error', 2000);
          }
        };
          break;
        case '1': {
          const r = await adjustingEntry({
            dbname,
            Data_ID: accountYearRef.current,
            editUser: username,
          })
          if (r) {
            notify("完成计算", "success", 2000)
            reloadTreeAndTable();
            AccountRef.current.show('0');
          }
        }
          break;
      }
    },
  };


  const onSelectionChangedKM = (e: any) => {
    setSubjectLevel(e.selectedItem)
  }

  const refreshSubject = (r: boolean) => {
    if (r) {
      reloadTreeAndTable();
      AccountRef.current.show('0')
    }
  }
  const MonthRefresh = (r: any) => {
    if (r) {
      getSubjectSDBDatas();
    }
  }

  return (
    <div style={{ width: "100%", height: "calc(100% - 50px)", position: 'absolute' }}>
      <DevToolBar.Default className='ItemStyle'>
        <Item location="before">
          {useMemo(() => {
            if (selDefaultValue && TextValue) {
              return <div style={Divstyle}>
                <div style={Divstyle}>
                  <div style={Titlestyle}>{intl('report.subject.account', '账套:')}</div>
                  <SelectBox
                    width={resizeWidth <= 1467 ? 100 : 200}
                    dataSource={accountYearData}
                    displayExpr='displayName'
                    valueExpr='displayName'
                    defaultValue={selDefaultValue}
                    onSelectionChanged={onSelectionChangeds}
                    dropDownOptions={{
                      width: '350px'
                    }} />
                </div>
                <div style={{ ...Divstyle, paddingLeft: 20 }}>
                  <div style={Titlestyle}>{intl('report.subject.EndMonth', '截止月份:')}</div>
                  <TextBox
                    style={{ position: 'relative' }}
                    width={90}
                    value={TextValue}
                    defaultValue={TextValue}
                    placeholder="选择..."
                  >
                    <span style={{ position: 'absolute', right: '5px', top: '5px', zIndex: '2' }}>
                      <CpasIcon
                        type="icon-yuefenzhongzhi"
                        onClick={async () => {
                          ToResetRef.current.show(
                            {
                              args: { title: '重新设置截止月份' },
                              OkCallback: () => {
                                reloadTreeAndTable();
                                AccountRef.current.show('0')
                              }
                            }, `${TextValue}`,
                          );
                        }}
                      />
                    </span>
                  </TextBox>
                </div>
              </div>
            }
            return <div>loading...</div>
          }, [timeData, TextValue])}

        </Item>
        <Item location="before">
          <div style={Divstyle}>
            <div style={Titlestyle}>科目级次:</div>
            <SelectBox width={90}
              items={SubjectLevelData} value={subjectLevel} defaultValue='全部'
              onSelectionChanged={onSelectionChangedKM}
            />
          </div>
        </Item>
        <Item location="before">
          <div style={Divstyle}>
            <div style={Titlestyle}>账项类型:</div>
            <DropDownBoxList
              widthStyle={resizeWidth}
            />
          </div>
        </Item>
        <Item location="before">
          <div style={Divstyle}>
            {/* defaultValue={true}  默认选中 */}
            <CheckBox className='SubjectsCheckBox' defaultValue={true} onValueChanged={(e: any) => {
              setCheckBoxVaue(!e.value)
              AccountRef.current.show('0')
            }} /><span style={{ marginLeft: "10px" }}>仅显示总账</span>
          </div>
        </Item>
        <Item location="after">
          <div>
            <DevGridSearchIpt
              devGridRefs={dataRef}
              placeholder=""
              width={resizeWidth <= 1467 ? 130 : 200}
              className="TextBoxButtons_Style"
              buttons={[
                {
                  location: "before",
                  name: "search",
                  options: {
                    icon: "iconfont icon-search",
                    disabled: true,
                  },
                },
              ]}
            />
          </div>
        </Item>
        <Item location="after" >
          <div style={Divstyle}>
            <div className="IconRefresh_Style">
              <CpasIcon type='icon-refresh' fontSize={16} onClick={() => {
                setSubjectLevel("全部")
                reloadTreeAndTable();
                AccountRef.current.show('0');
              }} />
            </div>
          </div>
        </Item>
        <Item widget="dxMenu" location="after" options={changeCategoryMenuOptions} cssClass='AgainMenu' />
      </DevToolBar.Default>
      <div style={{ display: 'flex', width: '99%', height: "100%", borderTop: "1px solid #ccc", marginTop: '-3px' }}>
        {
          useMemo(() => {
            return <AccountTabs
              // Tabdata={SubjectData}
              AccountDataID={accountYear ? accountYear : accountYearRef.current}
              ref={AccountRef}
              changeDataFun={changeDataFun}
            />
          }, [accountYear])
        }

        <div style={{ width: '99%', }}>
          {
            useMemo(() => {
              return <TableComponents
                AccountDataID={accountYear ? accountYear : accountYearRef.current}
                AccountTreeList={accountTreeList}
                ref={DataTreeRef}
                SubjectSDBData={subjectSDBData}
                SelectTableComponents
                refreshSubject={refreshSubject}
                timeData={timeData}
              />
            }, [accountTreeList, timeData, subjectSDBData, subjectLevel, accountYear])
          }
        </div>
      </div>
      {
        useMemo(() => {
          return <ReportFinancialToResetMonth ref={ToResetRef} MonthRefresh={MonthRefresh} Content={Content} AccountDataID={accountYear ? accountYear : accountYearRef.current} />
        }, [Content, accountYear])
      }
      <LoadPanel
        visible={isShowGloablLoadInit}
        showIndicator={true}
        showPane={true}
      />
    </div>)
};
export default ReportFinancial;